package com.kedsoft.docms.controller;

import com.kedsoft.docms.common.MessageResult;
import com.kedsoft.docms.entity.Template;
import com.kedsoft.docms.service.TemplateService;
import com.kedsoft.docms.util.FileUtils;
import com.kedsoft.docms.vo.PageVo;
import com.kedsoft.docms.vo.Pagination;
import com.kedsoft.docms.vo.TemplateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/11/23.
 */
@Controller
@RequestMapping("/template")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @RequestMapping(value = "index")
    public String index() {
        return "template/index";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Template> getPageList(Pagination<Template> pagination, @RequestParam(required = false) String username, @RequestParam(required = false) String nickname){
        Map<String, Object> query = new HashMap<>();
        query.put("filename", username);
        query.put("nickname", nickname);
        templateService.pageList(pagination,query);
        PageVo<Template> pageVo = new PageVo<>(pagination.getItems(),pagination.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "form")
    public String form(){
        return "template/form";
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(TemplateVo param){
        Template bean = new Template();
        bean.setFilename(param.getFilename());
        bean.setNickname(param.getNickname());
        bean.setFileaddress(param.getFileaddress());
        bean.setStatus(param.getStatus());
        bean.setCrtime(new Date());
        templateService.insert(bean);
        //创建模版文件
        try {
            FileUtils.createDir(param.getFileaddress());
            FileUtils.createFile(param.getFileaddress()+"/",param.getFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return MessageResult.getSuccess("添加数据成功");
    }
}
